//
//  CellViewController.m
//  ijkPlayer
//
//  Created by apple on 2018/6/5.
//  Copyright © 2018年 锦. All rights reserved.
//
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define kStatusHeight   [[UIApplication sharedApplication]statusBarFrame].size.height
#import "CellViewController.h"
#import "VideoCell.h"
#import "IJKPlayVideoView.h"
#import "VideoLisetCell.h"
#import "UIImageView+WebCache.h"

@interface CellViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (strong, nonatomic)UICollectionView       *collectionView;

/**
 记录点击过的cell
 */
@property (nonatomic, assign)  NSInteger         lastIndex;
@property (nonatomic, strong)  NSMutableArray    *selectedArr;
@property (nonatomic, assign)  NSRange           lastRange;
/**
 播放器显示view
 */
@property (nonatomic, strong)IJKPlayVideoView   *ijkPlayerView;
@end

@implementation CellViewController
{
    /** 测试视频 */
    NSArray *_videoPathArr;
    NSArray *_videoNameArr;
    NSArray *_imageNameArr;
    NSArray *_imageURLStrArr;
    NSMutableArray *_timeArr;
    NSMutableArray *_totalTimeArr;
    BOOL _notFirst;
    BOOL _newPlayer;
    
}
- (BOOL)prefersStatusBarHidden {
    return YES;
}
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
    
}
- (void)viewDidDisappear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = NO;
    [self.ijkPlayerView shutdown];
    [self.ijkPlayerView clearCache];
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
    [[SDImageCache sharedImageCache] clearMemory];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self testData];
    
    /**
     播放器View
     */
    self.ijkPlayerView = [[IJKPlayVideoView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT )];
    self.ijkPlayerView.backgroundColor = [UIColor clearColor];
    _ijkPlayerView.isFill = YES;
    
    [self addDetailsCollectionView];
    

    //  1. 添加播放状态改变的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackStateDidChange:) name:IJKMPMoviePlayerPlaybackStateDidChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadStateDidChange:) name:IJKMPMoviePlayerLoadStateDidChangeNotification object:nil];
    
    
    
    UIButton *b = [[UIButton alloc]initWithFrame:CGRectMake(0, 44, 100, 34)];
    b.backgroundColor = [UIColor blueColor];
    [b setTitle:@"< 返回 古德" forState:UIControlStateNormal];
    [b addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:b];
    
}
- (void)loadStateDidChange:(NSNotification*)notification
{
    //    MPMovieLoadStateUnknown        = 0,
    //    MPMovieLoadStatePlayable       = 1 << 0,
    //    MPMovieLoadStatePlaythroughOK  = 1 << 1, // Playback will be automatically started in this state when shouldAutoplay is YES
    //    MPMovieLoadStateStalled        = 1 << 2, // Playback will be automatically paused in this state, if started
    
    IJKMPMovieLoadState loadState = self.ijkPlayerView.player.loadState;
    
    if ((loadState & IJKMPMovieLoadStatePlaythroughOK) != 0) {
        NSLog(@"loadStateDidChange: IJKMPMovieLoadStatePlaythroughOK: %d\n", (int)loadState);
    } else if ((loadState & IJKMPMovieLoadStateStalled) != 0) {
        NSLog(@"loadStateDidChange: IJKMPMovieLoadStateStalled: %d\n", (int)loadState);
    } else if ((loadState & IJKMPMovieLoadStatePlayable) != 0) {
        NSLog(@"loadStateDidChange: IJKMPMovieLoadStatePlayable: %d\n", (int)loadState);
    }else
    {
        NSLog(@"loadStateDidChange: ???: %d\n", (int)loadState);
    }
}


- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void) playbackStateDidChange:(NSNotification *) notification {
    
    //    NSLog(@"%@",notification);
    //    IJKMPMoviePlaybackStateStopped,        停止
    //    IJKMPMoviePlaybackStatePlaying,        正在播放
    //    IJKMPMoviePlaybackStatePaused,         暂停
    //    IJKMPMoviePlaybackStateInterrupted,    打断
    //    IJKMPMoviePlaybackStateSeekingForward, 快进
    //    IJKMPMoviePlaybackStateSeekingBackward 快退
    
    
    switch (self.ijkPlayerView.player.playbackState) {
        case IJKMPMoviePlaybackStateStopped:
            NSLog(@"停止");
            break;
        case IJKMPMoviePlaybackStatePlaying:
            NSLog(@"正在播放");
            
//            [self.ijkPlayerView pause];
//            [self.ijkPlayerView seekTo:0];
            break;
        case IJKMPMoviePlaybackStatePaused:
            NSLog(@"暂停");
            break;
        case IJKMPMoviePlaybackStateInterrupted:
            NSLog(@"打断");
            break;
        case IJKMPMoviePlaybackStateSeekingForward:
            NSLog(@"快进");
            break;
        case IJKMPMoviePlaybackStateSeekingBackward:
            NSLog(@"快退");
            break;
        default:
            break;
    }
}


#pragma mark    ======== UICollectionView ========

- (void)addDetailsCollectionView {
    //collectionView
    UICollectionViewFlowLayout* layout2 = [[UICollectionViewFlowLayout alloc] init];
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    layout2.itemSize = CGSizeMake(width, height);
    
    
    //设置分区的头视图和尾视图是否始终固定在屏幕上边和下边
    //    layout2.sectionFootersPinToVisibleBounds = YES;
    //    layout2.sectionHeadersPinToVisibleBounds = YES;
    
    
    //竖直滚动
    layout2.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    // 设置额外滚动区域
    layout2.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    // 设置cell间距
    //设置水平间距, 注意点:系统可能会跳转(计算不准确)
    layout2.minimumInteritemSpacing = 0;
    //设置垂直间距
    layout2.minimumLineSpacing = 0;
    
    
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout2];//self.view.frame.size.width *9/16
    
    //设置背景颜色
    self.collectionView.backgroundColor = [UIColor clearColor];
    
    //    UIGestureRecognizer *gestur = [[UIGestureRecognizer alloc]init];
    //    gestur.delegate=self;
    //    [self.musicCollectionView addGestureRecognizer:gestur];
    
    
    
    // 设置数据源,展示数据
    self.collectionView.dataSource = self;
    //设置代理,监听
    self.collectionView.delegate = self;
    self.collectionView.alwaysBounceVertical = YES;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    // 注册cell
    [self.collectionView registerClass:[VideoCell class] forCellWithReuseIdentifier:@"VideoCell"];
    
    
    /* 设置UICollectionView的属性 */
    //设置滚动条
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    
    //设置是否需要弹簧效果
    self.collectionView.bounces = NO;
    
    [self.view addSubview:_collectionView];
}

#pragma mark    ======== UICollectionViewDelegate ========
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

// 告诉系统每组多少个
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _videoPathArr.count;
}

// 告诉系统每个Cell如何显示
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 1.从缓存池中取
    
    static NSString *cellID2 = @"VideoCell";
    VideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID2 forIndexPath:indexPath];
    NSLog(@"加载cell%ld",(long)indexPath.row);
    
    if (indexPath.row == 0 && !_notFirst) {
        
        _lastIndex = 0;        
        _ijkPlayerView.urlStr = _videoPathArr[0];
        if (_videoPathArr.count > 1) {
            [_ijkPlayerView setPrestrainUrlWithString:_videoPathArr[1]];
        }
        _ijkPlayerView.player.shouldShowHudView = YES;
        //[cell play:nil];
        [_ijkPlayerView removeFromSuperview];
        [cell.contentView insertSubview:_ijkPlayerView belowSubview:cell.selectedView];
        _lastRange = NSMakeRange(0 , self.view.frame.size.height);
        [_collectionView setContentOffset:CGPointMake(0, self.view.frame.size.height)];
    }
    if (indexPath.row == 1 && !_notFirst) {
        _notFirst = YES;
        [_collectionView setContentOffset:CGPointMake(0, 0)];
    }

  //  [cell.imageView sd_setImageWithURL:[NSURL URLWithString:_imageURLStrArr[indexPath.row]]];
  
    
    
    cell.nameLabel.text = [NSString stringWithFormat:@"视频 %ld",(long)indexPath.row];
    return cell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.ijkPlayerView isPlaying]) {
        [self.ijkPlayerView pause];
    }else{
        
        if (_newPlayer) {
            VideoCell *cell = (VideoCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:_lastIndex inSection:0]];
            [cell.imageView addSubview:_ijkPlayerView];
            _newPlayer = NO;
        }
        [self.ijkPlayerView play];
        
    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView.contentOffset.y < _lastRange.location || scrollView.contentOffset.y > _lastRange.length) {
        [self.ijkPlayerView pause];
        [self.ijkPlayerView seekTo:0];
        [self.ijkPlayerView removeFromSuperview];
        _newPlayer = YES;
    }

}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    
    int visableIndex = (int )(scrollView.contentOffset.y / self.view.frame.size.height);
    
    if (_lastIndex == visableIndex) {
        return;
    }
    _lastRange = NSMakeRange(scrollView.contentOffset.y - self.view.frame.size.height , scrollView.contentOffset.y + self.view.frame.size.height);
    VideoCell *cell = (VideoCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:visableIndex inSection:0]];
    
    _lastIndex = visableIndex;
    _ijkPlayerView.urlStr = _videoPathArr[visableIndex];
    if (visableIndex + 1 < _videoPathArr.count) {
        [_ijkPlayerView setPrestrainUrlWithString:_videoPathArr[visableIndex + 1]];
    }
    if (visableIndex - 1 > 0) {
        [_ijkPlayerView setPrestrainLastUrlWithString:_videoPathArr[visableIndex - 1]];
    }

    _ijkPlayerView.player.shouldShowHudView = YES;
    [cell.contentView insertSubview:_ijkPlayerView belowSubview:cell.selectedView];

}


- (void)testData {
    
    
    
    
    NSString *path5 = @"http://123.206.58.253/media/big.mp4";
    
    NSString *path6 = @"http://123.206.58.253/test/a.m3u8";
    NSString *path7 = @"http://123.206.58.253/origin/gtv.m3u8";
    NSString *path8 = @"http://ugc.dls.migudm.cn/Client/ugc/funshoot/product/2018050711/23995822851808499.mp4?st=IS3-01YDCvkPtpYGSfcSgQ&e=1535457284";
    NSString *path9 = @"http://ugc.dls.migudm.cn/Client/ugc/funshoot/product/2018050711/23996843548906685.mp4?st=utZegmktnXrYns_RrIc52g&e=1535457284";
    _videoPathArr = [NSArray arrayWithObjects:path5,path6,path8,path9,path7, nil];
    
    NSString *imageURL1 = @"http://ugc.dls.migudm.cn/Client/image/funshoot/product/2018060820/bf10b8e93bdb4e2e9dc0ed26cbac2560.jpg";
    
    NSString *imageURL2 = @"http://ugc.dls.migudm.cn/Client/image/funshoot/product/2018060419/0a7ed1c80b264b38afd5459d1f2a8db7.jpg";
    
    NSString *imageURL3 = @"http://ugc.dls.migudm.cn/Client/image/funshoot/product/2018060709/111915661fcc4ad2964e45abfc133324.jpg";
    
    NSString *imageURL4 = @"http://ugc.dls.migudm.cn/Client/image/funshoot/product/2018060615/84bf1d48cc174f338ee160d2f87622e1.jpg";
    
    NSString *imageURL5 = @"http://ugc.dls.migudm.cn/Client/image/funshoot/product/2018060821/93c2042a3af64383be2a3b719a39290b.jpg";
    
    NSString *imageURL6 = @"http://ugc.dls.migudm.cn/Client/image/funshoot/product/2018060616/eee7685a01a440eda7d1487974c60f7a.jpg";
    
    _imageURLStrArr = [NSArray arrayWithObjects:imageURL1,imageURL2,imageURL3,imageURL4,imageURL5, imageURL6,imageURL5,imageURL4,imageURL2,imageURL1,nil];
    
    
    _selectedArr = [NSMutableArray arrayWithObjects:@"0",@"0",@"0",@"0",@"0",@"0",@"0",@"0",@"0",@"0",@"0",@"0",@"0",@"0",@"0",@"0",@"0",@"0", nil];
    
    _imageNameArr = [NSArray arrayWithObjects:@"cell0.PNG",@"migu1.jpg",@"migu2.jpg",@"migu3.jpg",@"migu4.jpg",@"migu5.jpg",@"migu6.jpg",@"cell0.PNG",@"cell0.PNG",@"cell0.PNG",@"cell0.PNG",@"cell0.PNG",@"cell0.PNG",@"cell0.PNG",@"cell0.PNG",@"cell0.PNG",@"cell0.PNG",@"cell0.PNG", nil];
    
    
    
    _timeArr = [NSMutableArray array];
    _totalTimeArr = [NSMutableArray array];
    for (int i = 0; i<6; i++) {
        NSMutableArray *arr = [NSMutableArray array];
        [_timeArr addObject:arr];
        
        CGFloat t = 0;
        [_totalTimeArr addObject:[NSNumber numberWithFloat:t]];
    }
}



- (void)dealloc {
    NSLog(@"dealloc");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
